package com.sanyue.imitation;

import org.junit.Test;

import java.util.HashMap;

/**
 * @author sanyue
 * @version 1.0
 * @description: TODO-1
 * @date 2022/1/22 下午4:33
 */
public class TwoSum {
    @Test
    public void solve() {
        int[] ans = twoSum2(new int[]{1,2,3,4,3}, 8);
        if (ans.length > 0) {
            System.out.println(ans[0] + ":" + ans[1]);
        }else {
            System.out.println(ans.length == 0);
        }
    }

    //解法1：双重循环 时间复杂的O(n^2)
    //在所有 Java 提交中击败了9%的用户
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == target - nums[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{};
    }

    //解法2 利用hash表进行一个存储 快速获取 O(n)
    //在所有 Java 提交中击败了99.36%的用户
    public int[] twoSum2(int[] nums, int target) {
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();//key:value value:index
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }else {
                map.put(nums[i],i);
            }
        }
        return new int[]{};
    }


}
